package com.iot.protoocol;

import com.iot.messaage.DeviceMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @author Administrator
 */
public class ProtocolLoader {
    private static final Logger log = LoggerFactory.getLogger(ProtocolLoader.class);
    private String realPath; // 假设 realPath 是 JAR 文件的路径

    public ProtocolLoader(String realPath) {
        this.realPath = realPath;
    }

    private DeviceMessageDecoder processJar() throws Exception {
        // 加载本地协议 JAR 文件并实例化 DeviceMessageDecoder
        URLClassLoader classLoader = loadLocalProtocol(realPath);
        try {
            // 遍历 JAR 文件中的类，找到 DeviceMessageDecoder 的实现类
            try (ZipFile zipFile = new ZipFile(realPath)) {
                Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();
                    if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
                        String className = entry.getName().replace(".class", "").replace("/", ".");
                        Class<?> clazz = classLoader.loadClass(className);
                        if (DeviceMessageDecoder.class.isAssignableFrom(clazz)) {
                            return (DeviceMessageDecoder) clazz.getDeclaredConstructor().newInstance();
                        }
                    }
                }
            }
            throw new ClassNotFoundException("未找到 DeviceMessageDecoder 的实现类");
        } finally {
            // 在 finally 块中释放类加载器资源
            classLoader.close();
        }
    }

    private URLClassLoader loadLocalProtocol(String filePath) throws Exception {
        // 创建 URLClassLoader 加载本地 JAR 文件
        File jarFile = new File(filePath);
        if (!jarFile.exists()) {
            throw new FileNotFoundException("JAR 文件不存在：" + filePath);
        }
        URL url = jarFile.toURI().toURL();
        return new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader());
    }
}